package com.csnf.mall.filter;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.InputStream;

public class MyBatisContextListener implements ServletContextListener {
    //servletContext对象创建后会调用此方法
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            //加载mybatis的运行环境
            //加载mybatis-config.xml
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);

            //创建sqlSessionFactory
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            //创建sqlSession
            SqlSession sqlSession = sessionFactory.openSession();

            //把sqlSession对象撞到servletContext中
            ServletContext servletContext = sce.getServletContext();
            servletContext.setAttribute("sqlSession", sqlSession);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}